<script setup lang="ts" name="PhysicalExaminationRegister">
import {ref, reactive, onActivated, onBeforeMount, onDeactivated, watch, computed} from 'vue'
import {RowOperbuttons} from '@/components/dTable/dTable'
import {SearchButton, SearchFromItem, OperButton} from '@/components/dTable/dHeader'
import dTablePromote from '@/components/dTable/dTablePromote.vue'
import dTable from '@/components/dTable/dTable.vue'
import dFooter from '@/components/dTable/dFooter.vue'
import dHeader from '@/components/dTable/dHeader.vue'
import pageContainer from '@/components/pageContainer.vue'
import operation from '@/components/dTable/components/operation.vue'
import dFrom from '@/components/dFrom/dFrom.vue'
import dIcon from '@/components/dIcon.vue'
import {ElInput, ElMessage, FormRules} from 'element-plus'
import type {Operation as Oper, HeaderData} from '@/components/dTable/dTable'
import {ColorRed} from '@/api/config'
import additions from './additions.vue'
import selectPackage from './selectPackage.vue'
import addArchives from '@/views/pages/publicHealthExamination/residentArchives/addArchives.vue'
import {showCLodopTips, loadCLodop, checkPrint} from '@/util/cLodop'
import {HXGCReader} from '@/util/idReader'
import {ResidentList} from '@/api/publicHealthExamination/residentArchives'
import {SeleteData, ColorTheme} from '@/api/config'
import {getIdCardInfor, transfDicArrData, IdCard, NoNumber, PhoneNumber, Number as NumberRegExp, NotLeadingAndTrailingSpaces, getYearMonthDayStr} from '@/util/common'
import {getTeamListAll, SelectTeamLsit} from '@/api/publicHealthExamination/communitySettings'
import {FromItem} from '@/components/dFrom/dFrom'
import {
  batchPrintBarcodes,
  batchPrintGuideSheet,
  CheckupRegisterList,
  saveCheckupRegister,
  getCheckupRegisterList,
  type CheckupRegisterPapams,
  CheckupRegisterForm,
  RegisterItemGroups,
  cancelCheckupRegister,
  PackageList,
  AddItemGroupList,
  deleteAddItemGroup,
  Situation,
  getPersonalByIdNo,
  getPrintBarcodes,
  getPrintGuideSheets,
  getDefaultPackage,
  getJudgeSituation,
  GetPackageList
} from '@/api/publicHealthExamination/physicalExaminationRegister'
import userCommon from '@/store/common'
import useUser from '@/store/user'
import {showMessageBox} from '@/util/element'
const common = userCommon.setup().store

// 表格加载
const showLoading = ref<boolean>(false)

// 底部操作加载
const showFooterLoading = ref<boolean>(false)

//左侧数据
const tableData = ref<Array<CheckupRegisterList>>([])

// 保存选中的行的id
const selectedRowId = ref<string | undefined>(undefined)

//右侧数据
const rightTableData = ref<Array<RegisterItemGroups & RowOperbuttons>>([])

//默认选中
const defualtSeleted = ref<CheckupRegisterList | undefined>(undefined)

// 选择套餐弹窗
const showSelectPackageDialog = ref<boolean>(false)

// 加项弹窗
const showAdditionsDialog = ref<boolean>(false)

// 编辑人员弹窗
const showArchivesDialog = ref<boolean>(false)

// 暂存登记id
const registerId = ref('')

// 身份证读取实例
const IDReader = ref()

// 人员列表表单实例
const personalTableRef = ref()

// 套餐id
const packageId = ref('')
// 是否下乡体验模式，(医院内网环境)
const situation = ref(common.$state.situation === 'outer' ? true : false)

// 体检套餐里面的项目组合列表，用于排除可选项目组合
const packageItemList = ref<Array<RegisterItemGroups>>([])
// 已选加项项目组合，用于回显
const selectedItemList = ref<Array<RegisterItemGroups>>([])

// 登记体检状态
const registerStatus = ref<number>()

// 勾选的体检登记id
const selectionIdList = ref<Array<string>>([])
//勾选数据
const selectionData = ref<Array<CheckupRegisterList>>([])

// 民族下拉
const seleteNationData = ref<Array<SeleteData>>([])
// 性别下拉
const selectGenderData = ref<Array<SeleteData>>([
  {label: '男', value: '男'},
  {label: '女', value: '女'}
])
// 社区下拉
const selectTeamLsit = ref<Array<SelectTeamLsit>>([])

// 既往史下拉
const pastHistoryLsit = ref<Array<SeleteData>>([])
// 切换下乡体检模式加载
const situationLoading = ref<boolean>(false)

//表单清除控制
const resetFieldsFlag = ref(false)

const validateFlag = ref(false)

//信息
const formData = reactive<CheckupRegisterForm>({
  personName: '', // 姓名
  gender: '', //性别
  age: '', //年龄
  idNo: '', // 身份证号
  nation: '', // 民族
  phone: '', // 手机号
  portrait: '', // 头像
  teamId: '', // 社区id
  teamName: '', // 社区名称
  address: '' // 地址
})

const searchFromData = reactive<CheckupRegisterPapams>({
  phyDate: [getYearMonthDayStr(Date.now()), getYearMonthDayStr(Date.now())]
})

// 头部搜索表单
const searchFromItems = ref<Array<SearchFromItem>>([
  {
    label: '体检日期',
    placeholder: ['开始日期', '结束日期'],
    type: 'antdRange',
    prop: 'phyDate',
    showTime: false,
    changeSubmit: true,
    notClearable: true,
    dateFormat: 'YYYY-MM-DD',
    style: {width: '320px'}
  },
  {
    label: '社区',
    placeholder: '请选择社区',
    type: 'selete',
    seleteData: selectTeamLsit.value,
    prop: 'teamId',
    changeSubmit: true
  },
  {
    label: '身份证号',
    type: 'slot',
    slotName: 'idNo',
    prop: 'idNo'
  },
  {
    label: '姓名',
    placeholder: '请输入姓名',
    type: 'input',
    prop: 'personName',
    enterSubmit: true
  }
])

// 登记信息表单项
const fromItems = ref<Array<FromItem>>([
  {
    label: '身份证号',
    placeholder: '请输入身份证号',
    prop: 'idNo',
    type: 'slot',
    slotName: 'idNo',
    style: {'grid-column': '1/4'}
  },
  {
    label: '联系电话',
    placeholder: '请输入联系电话',
    prop: 'phone',
    type: 'input',
    style: {'grid-column': '4', 'min-width': '192px'}
  },
  {
    label: '姓名',
    placeholder: '请输入姓名',
    prop: 'personName',
    type: 'input',
    style: {'grid-column': '1', 'min-width': '192px'}
  },
  {
    label: '性别',
    placeholder: '请选择性别',
    prop: 'gender',
    type: 'selete',
    disabled: true,
    seleteData: selectGenderData.value,
    style: {'grid-column': '2', 'min-width': '130px'}
  },
  {
    label: '年龄',
    placeholder: '请输入年龄',
    prop: 'age',
    type: 'slot',
    slotName: 'age',
    disabled: true,
    style: {'grid-column': '3', 'min-width': '155px'}
  },
  {
    label: '民族',
    placeholder: '请选择民族',
    prop: 'nation',
    type: 'selete',
    filterable: true,
    seleteData: seleteNationData.value,
    style: {'grid-column': '4', 'min-width': '192px'}
  },
  {
    label: '社区',
    placeholder: '请选择社区',
    prop: 'teamId',
    type: 'selete',
    filterable: true,
    seleteData: selectTeamLsit.value,
    style: {'grid-column': '1'}
  },
  {
    label: '居住地址',
    placeholder: '请输入居住地址',
    prop: 'address',
    type: 'input',
    style: {'grid-column': '2/4'}
  },
  {
    label: '既往史',
    placeholder: '请选择既往史',
    prop: 'pastHistory',
    type: 'selete',
    filterable: true,
    seleteData: pastHistoryLsit.value,
    style: {'grid-column': '4'}
  }
])

// 人员列表表头
const tableHeaderData = ref<Array<HeaderData>>([
  {
    prop: 'checkupNo',
    label: '体检号',
    columnType: 'text',
    align: 'left',
    'min-width': '100'
  },
  {
    prop: 'personName',
    label: '姓名',
    columnType: 'slot',
    align: 'left',
    'min-width': '80'
  },
  {
    prop: 'gender',
    label: '性别',
    columnType: 'text',
    align: 'left',
    'min-width': '80'
  },
  {
    prop: 'age',
    label: '年龄',
    columnType: 'text',
    align: 'left',
    'min-width': '80'
  },
  {
    prop: 'idNo',
    label: '身份证号',
    columnType: 'text',
    'min-width': '150'
  }
])

// 项目组合列表
const tableHeaderData2 = ref<Array<HeaderData>>([
  {
    prop: 'itemGroupName',
    label: '项目组合',
    columnType: 'text',
    align: 'left',
    'min-width': '250'
  },
  // {
  //   prop: 'price',
  //   label: '单价（元）',
  //   columnType: 'text',
  //   align: 'left',
  //   'min-width': '120'
  // },
  {
    prop: 'deptName',
    label: '科室',
    columnType: 'text',
    align: 'left',
    'min-width': '250'
  }
  // {
  //   prop: 'oper',
  //   label: '操作',
  //   columnType: 'slot',
  //   align: 'center',
  //   width: '70'
  // }
])

// 头部搜索表单规则
const searchFromRules = reactive<FormRules>({
  idNo: [
    {
      message: '长度应不超过18个字符',
      max: 18,
      trigger: ['change', 'blur']
    },
    {
      message: '请输入正确的身份证号码',
      pattern: IdCard,
      trigger: ['blur']
    }
  ],
  personName: [
    {
      message: '长度应不超过20个字符',
      max: 20,
      trigger: ['change', 'blur']
    },
    {
      message: '请输入汉字、字母、字符',
      pattern: NoNumber,
      trigger: ['change', 'blur']
    }
  ]
})

// 登记信息表单规则
const rules = reactive<FormRules>({
  idNo: [
    {required: true, message: '请输入身份证号码', trigger: ['change', 'blur']},
    {
      message: '长度应不超过18个字符',
      max: 18,
      trigger: ['change', 'blur']
    },
    {
      message: '请输入正确的身份证号码',
      pattern: IdCard,
      trigger: ['blur']
    }
  ],
  personName: [
    {required: true, message: '请输入姓名', trigger: ['change', 'blur']},
    {
      message: '长度应不超过20个字符',
      max: 20,
      trigger: ['change', 'blur']
    },
    {
      message: '请输入汉字、字母、字符',
      pattern: NoNumber,
      trigger: ['change', 'blur']
    }
  ],
  gender: [{required: true, message: '请选择性别', trigger: ['change', 'blur']}],
  phone: [
    {required: true, message: '请输入联系电话', trigger: ['change', 'blur']},
    {
      message: '长度应不超过11个字符',
      max: 11,
      trigger: ['change', 'blur']
    },
    {
      message: '请输入正确的联系电话',
      pattern: PhoneNumber,
      trigger: ['change', 'blur']
    }
  ],
  nation: [{required: true, message: '请选择民族', trigger: ['change', 'blur']}],
  teamId: [{required: true, message: '请选择社区', trigger: ['change', 'blur']}],
  age: [
    {required: true, message: '请输入年龄', trigger: ['change', 'blur']},
    {message: '请输入数字', pattern: NumberRegExp, trigger: ['change', 'blur']}
  ],
  address: [
    {required: true, message: '请输入居住地址', trigger: ['change', 'blur']},
    {
      message: '请输入汉字、字母、数字、字符，首尾不能为空',
      pattern: NotLeadingAndTrailingSpaces,
      trigger: ['change', 'blur']
    },
    {
      message: '长度应不超过100个字符',
      max: 100,
      trigger: ['change', 'blur']
    }
  ],
  pastHistory: [
    {
      message: '请输入汉字、字母、数字、字符，首尾不能为空',
      pattern: NotLeadingAndTrailingSpaces,
      trigger: ['change', 'blur']
    },
    {
      message: '长度应不超过200个字符',
      max: 200,
      trigger: ['change', 'blur']
    }
  ]
})

// 人员列表底部按钮
const footerButtonsLeft = ref<Array<OperButton>>([
  {label: '打印条码', type: 'noraml', code: 'printBarcode'},
  {label: '打印引导单', type: 'noraml', code: 'printGuideSheet'}
])

// 登记信息底部按钮
const footerButtonsRight = computed<Array<OperButton>>(() => {
  let footerBtn: Array<OperButton> = [
    {label: '登记', type: 'noraml', code: 'register'},
    {label: '修改套餐', type: 'noraml', code: 'selectPackage', disabled: !formData.age && !formData.gender},
    // {label: '加项', type: 'noraml', code: 'additions'},
    {
      label: '取消登记',
      type: 'noraml',
      plain: true,
      elType: 'danger',
      code: 'deregistration'
    }
  ]
  // 有登记状态的数据按钮为新增
  registerId.value && (footerBtn[0] = {label: '新增', type: 'noraml', code: 'add'})
  // 未登记的新数据才能选择套餐
  registerId.value &&
    (footerBtn = footerBtn.filter((item) => {
      return item.code !== 'selectPackage'
    }))
  // 已登记才能取消登记
  registerStatus.value !== 1 &&
    (footerBtn = footerBtn.filter((item) => {
      return item.code !== 'deregistration'
    }))
  // 已总检、已打印、已发放、拒检不能加项
  if (registerStatus.value === 3 || registerStatus.value === 4 || registerStatus.value === 5 || registerStatus.value === 6) {
    footerBtn = footerBtn.filter((item) => {
      return item.code !== 'additions'
    })
  }
  return footerBtn
})

// 项目组合操作按钮定义
const rowOperButtons: Array<Oper> = [
  {
    code: 'delete',
    label: '删除',
    iconConfig: {
      icon: 'common-delete',
      type: 'custom',
      color: ColorRed,
      size: 20
    }
  }
]

// 套餐名称
const checkupPackageName = ref('')
// 套餐价格
const checkupPackagePrice = ref(0)
// 加项名称
const addItemGroupName = ref('')
// 加项价格
const addItemGroupPrice = ref(0)

/**
 * @description: 获取登记信息
 * @return {*}
 */
const getRegisterInfor = (row: CheckupRegisterList) => {
  formData.idNo = row.idNo
  formData.personName = row.personName
  formData.gender = row.gender
  formData.age = row.age
  formData.nation = row.nation
  formData.phone = row.phone
  formData.teamId = row.teamId
  formData.teamName = row.teamName
  formData.address = row.address
  formData.pastHistory = row.pastHistory
  packageId.value = row.registerPackage?.packageId // 套餐id
  checkupPackageName.value = row.registerPackage?.packageName // 套餐名称
  checkupPackagePrice.value = row.registerPackage?.packagePrice // 套餐价格
  addItemGroupName.value = row.addItemGroupName // 加项名称
  addItemGroupPrice.value = row.addItemGroupPrice // 加项价格
  const dataArr: Array<RegisterItemGroups & RowOperbuttons> = []
  // 项目组合数据
  row.registerItemGroups?.length &&
    row.registerItemGroups.forEach((item) => {
      dataArr.push({...item, oper: item.isAdditional === 1 ? rowOperButtons : []})
    })
  // 项目组合数据
  rightTableData.value = dataArr
  // 已登记信息查看的时候禁用编辑
  fromItems.value.forEach((item) => {
    item.disabled = true
  })
}

/**
 * @description: 清空暂存的数据
 * @return {*}
 */
const clearData = () => {
  // 清空人员体检数据回显
  registerId.value = ''
  registerStatus.value = undefined
  resetFieldsFlag.value = !resetFieldsFlag.value // 清空表单数据及验证
  personalTableRef.value?.setSeleted(undefined)
  selectedRowId.value = undefined // 重置选中行
  packageId.value = ''
  rightTableData.value = []
  checkupPackageName.value = ''
  checkupPackagePrice.value = 0
  addItemGroupName.value = ''
  addItemGroupPrice.value = 0
  // 启用编辑
  fromItems.value.forEach((item) => {
    if (item.prop !== 'age' && item.prop !== 'gender') {
      item.disabled = false
    }
  })
}
/**
 * @description: 获取人员列表
 * @return {*}
 */
const getPersonnelList = () => {
  showLoading.value = true
  const params = {...searchFromData}
  searchFromData.phyDate?.length ? (params.startPhyDate = searchFromData.phyDate[0] + ' 00:00:00') : delete params.startPhyDate
  searchFromData.phyDate?.length ? (params.endPhyDate = searchFromData.phyDate[1] + ' 23:59:59') : delete params.endPhyDate
  delete params.phyDate
  getCheckupRegisterList(params)
    .then((res) => {
      const {data} = res.data
      tableData.value = data || []
      // 找到选中行的坐标
      const rowIndex = tableData.value.findIndex((item) => {
        return item.id === selectedRowId.value
      })
      personalTableRef.value?.setSeleted(tableData.value[rowIndex]) // 选中上次的行
    })
    .catch((err) => {
      console.warn(err)
      tableData.value = []
    })
    .finally(() => {
      showLoading.value = false
      if (tableData.value.length === 0) {
        clearData()
      }
    })
}

//行点击回调
const onRowClick = (row: CheckupRegisterList) => {
  if (row) {
    selectedRowId.value = row.id // 保存选中的行的id
    getRegisterInfor(row)
    registerId.value = row.id // 保存当前行id
    registerStatus.value = row.registerStatus // 保存登记状态
  } else {
    clearData()
  }
}

/**
 * @description: 选中套餐
 * @param {*} data 套餐数据
 * @return {*}
 */
const onSelectPackage = (data: PackageList) => {
  packageId.value = data.id // 套餐id
  checkupPackageName.value = data.packageName // 套餐名称
  checkupPackagePrice.value = data.packagePrice // 套餐价格
  const dataArr: Array<RegisterItemGroups & RowOperbuttons> = []
  // 遍历套餐项目组合
  data.itemGroupVOS?.length &&
    data.itemGroupVOS.forEach((item) => {
      dataArr.push({...item, oper: []})
    })
  // 更换套餐，保留加项的行
  rightTableData.value = rightTableData.value.filter((item) => {
    return item.isAdditional === 1
  })
  // 拼接新套餐和加项内容
  rightTableData.value = dataArr.concat(rightTableData.value)
}

/**
 * @description: 加项保存
 * @param {Array<AddItemGroupList>} data 加项列表
 * @return {*}
 */
const onAdditionsConfirm = (data?: Array<AddItemGroupList>) => {
  showAdditionsDialog.value = false
  const dataArr: Array<RegisterItemGroups & RowOperbuttons> = []
  data &&
    data.length &&
    data.forEach((item) => {
      item.isAdditional = 1 // 1表示加项
      dataArr.push({...item, oper: rowOperButtons})
      // 拼接加项名称
      addItemGroupName.value += `${addItemGroupName.value ? '、' : ''}${item.itemGroupName}`
      addItemGroupPrice.value += item.price // 价格累加
      addItemGroupPrice.value = Number(addItemGroupPrice.value.toFixed(2)) // 保留两位小数
    })
  // 拼接新套餐和加项内容
  rightTableData.value = rightTableData.value.concat(dataArr)
}

// 按钮搜索配置
const serachButtons = ref<Array<SearchButton>>([{type: 'search'}, {type: 'clear'}])

//编辑档案管理
const archivesData = reactive<Partial<ResidentList>>({})

// 清除勾选
const clearMultipleSelection = () => {
  selectionData.value = []
  selectionIdList.value = []
}

/**
 * @description: 批量打印条码
 * @return {*}
 */
const onPrintBarcodes = () => {
  showFooterLoading.value = true
  const params = {ids: selectionIdList.value}
  getPrintBarcodes(params)
    .then((res) => {
      const {data} = res.data || []
      batchPrintBarcodes(data)
        .then(() => {
          ElMessage.success('条码打印成功!')
          clearMultipleSelection() // 清除勾选
        })
        .catch((err) => {
          console.warn(err)
        })
        .finally(() => {
          showFooterLoading.value = false
        })
    })
    .catch((error) => {
      console.warn(error)
      showFooterLoading.value = false
    })
}

/**
 * @description: 批量打印引导单
 * @return {*}
 */
const onPrintGuideShee = () => {
  showFooterLoading.value = true
  const params = selectionIdList.value
  getPrintGuideSheets(params)
    .then((res) => {
      const {data} = res.data || []
      batchPrintGuideSheet(data)
        .then(() => {
          ElMessage.success('引导单打印成功!')
          clearMultipleSelection() // 清除勾选
        })
        .catch((err) => {
          console.warn(err)
        })
        .finally(() => {
          showFooterLoading.value = false
        })
    })
    .catch((error) => {
      console.warn(error)
      showFooterLoading.value = false
    })
}

/**
 * @description: 发起登记请求
 * @param {*} params // form表单数据
 * @return {*}
 */
const onSaveCheckupRegister = (params: CheckupRegisterForm) => {
  showLoading.value = true
  saveCheckupRegister({situation: situation.value ? Situation.OUTER : Situation.INNER}, params)
    .then((res) => {
      ElMessage.success('登记成功！')
      clearData()
      getPersonnelList()
      const {data} = res.data
      selectionIdList.value = data?.id ? [data?.id] : [] // 打印的id
      // 如果有错误信息，延迟显示，不然会重叠
      if (data?.errorMsg) {
        const timer = setTimeout(() => {
          ElMessage.error(data?.errorMsg)
          timer && clearTimeout(timer)
        }, 0)
      }
      // 判断是否选择条码打印机
      if (!showCLodopTips() || !checkPrint('barcode')) return
      onPrintBarcodes()
      // 判断是否选择pdf打印机
      if (!showCLodopTips() || !checkPrint('pdf')) return
      onPrintGuideShee()
    })
    .catch((error) => {
      console.warn(error)
    })
    .finally(() => {
      showLoading.value = false
    })
}

//表单验证通过事件
const onRegister = () => {
  const params = {...formData}
  params.packageId = packageId.value
  if (!params.packageId) {
    ElMessage.error('请选择套餐!')
    return
  }
  if (formData.age < 65) {
    showMessageBox(`该居民当前年龄${formData.age}岁小于65岁，是否继续进行登记？`, {title: '提示', mesageType: 'base'})
      .then(() => {
        onSaveCheckupRegister(params)
      })
      .catch((error) => {
        console.warn(error)
      })
  } else {
    onSaveCheckupRegister(params)
  }
}

/**
 * @description: 头部表单查询
 * @return {*}
 */
const onSubmit = () => {
  getPersonnelList()
}

/**
 * @description: 头部搜索框读取身份证号
 * @return {*}
 */
const onReadIdCardHeader = () => {
  IDReader.value &&
    IDReader.value
      .readIdCard()
      .then((res) => {
        searchFromData.idNo = res.idNum // 身份证号
        getPersonnelList()
      })
      .catch((err) => {
        console.warn(err)
      })
}

/**
 * @description: 头部表单清空
 * @return {*}
 */
const onFormClear = () => {
  resetFieldsFlag.value = !resetFieldsFlag.value // 清空表单数据
  selectedRowId.value = undefined // 重置选中行
  searchFromData.phyDate = [getYearMonthDayStr(Date.now()), getYearMonthDayStr(Date.now())]
  clearData()
  getPersonnelList()
}

//操作插槽事件（编辑，删除）事件
const cellOperation = (code: string, row: RegisterItemGroups) => {
  if (code === 'delete') {
    showMessageBox('是否确认取消此加项？', {title: '提示', mesageType: 'base'})
      .then(() => {
        // 根据登记id判断当前是已登记状态还是新增登记状态，如果已经登记则从后端删除加项，如果新增登记前端删除
        if (registerId.value) {
          deleteAddItemGroup({registerItemGroupId: row.id}).then(() => {
            ElMessage.success('删除成功！')
            getPersonnelList()
          })
        } else {
          addItemGroupName.value = '' // 先重置
          addItemGroupPrice.value = 0 // 先重置
          rightTableData.value = rightTableData.value.filter((item) => {
            // 拼接加项名称
            if (item.id !== row.id && item.isAdditional === 1) {
              addItemGroupName.value += `${addItemGroupName.value ? '、' : ''}${item.itemGroupName}`
              addItemGroupPrice.value += item.price // 价格累加
              addItemGroupPrice.value = Number(addItemGroupPrice.value.toFixed(2)) // 保留两位小数
            }
            return item.id !== row.id
          })
        }
      })
      .catch((error) => {
        console.warn(error)
      })
  }
}

/**
 * @description: 打开档案管理人员编辑
 * @param {*} idNo
 * @return {*}
 */
const openArchivesDialog = (idNo: string) => {
  getPersonalByIdNo({idNo})
    .then((res) => {
      const {data} = res.data
      // 能否在社区下拉中找到该社区
      const index = selectTeamLsit.value.findIndex((item) => {
        return item.value === data.teamId
      })
      archivesData.id = data.id
      archivesData.name = data.name
      archivesData.age = data.age
      archivesData.gender = data.gender
      archivesData.idNo = data.idNo
      archivesData.nation = data.nation
      archivesData.phone = data.phone
      archivesData.portrait = data.portrait
      archivesData.pastHistory = data.pastHistory
      // 社区被删除了就置空社区id
      archivesData.teamId = index !== -1 ? data.teamId : ''
      archivesData.address = data.address
      showArchivesDialog.value = true
    })
    .catch((err) => {
      console.warn(err)
    })
}

/**
 * @description: 关闭人员修改弹窗
 * @return {*}
 */
const onArchivesDialogClose = () => {
  showArchivesDialog.value = false
  onSubmit()
}

/**
 * @description: 勾选
 * @param {*} rows
 * @return {*}
 */
const onMultipleSelection = (rows: Array<CheckupRegisterList>) => {
  selectionData.value = rows
  selectionIdList.value = rows.map((item) => {
    return item.id
  })
}

/**
 * @description: 左侧列表底部按钮
 * @param {*} code 按钮名
 * @return {*}
 */
const onOperationLeft = (code: string) => {
  switch (code) {
  // 打印条码
  case 'printBarcode':
    if (selectionIdList.value.length === 0) {
      ElMessage.error('请勾选数据！')
    } else {
      // 判断是否选择条码打印机
      if (!showCLodopTips() || !checkPrint('barcode')) return
      onPrintBarcodes()
    }
    break
    // 打印引导单
  case 'printGuideSheet':
    if (selectionData.value.length === 0) {
      ElMessage.error('请勾选数据！')
    } else {
      if (!showCLodopTips() || !checkPrint('pdf')) return
      onPrintGuideShee()
    }
    break
  }
}

/**
 * @description: 身份证读卡器
 * @return {*}
 */
const onReadIdCard = () => {
  IDReader.value &&
    IDReader.value
      .readIdCard()
      .then((res) => {
        let nation
        // 遍历民族字典，拿到字典值
        seleteNationData.value.forEach((item) => {
          item.label === res.nation + '族' && (nation = item.value)
        })
        formData.idNo = res.idNum // 身份证号
        formData.personName = res.name // 姓名
        formData.nation = nation // 民族
        formData.address = res.address // 地址
        formData.portrait = res.photo // 头像
      })
      .catch((err) => {
        console.warn(err)
      })
}

/**
 * @description: 取消登记
 * @return {*}
 */
const onCancelRegister = () => {
  cancelCheckupRegister({checkupRegisterId: registerId.value}).then(() => {
    getPersonnelList()
    ElMessage.success('取消登记成功!')
  })
}

/**
 * @description: 右侧列表底部操作
 * @param {*} code 按钮名
 * @return {*}
 */
const onOperationRight = (code: string) => {
  switch (code) {
  // 登记
  case 'register':
    validateFlag.value = !validateFlag.value
    break
    // 新增
  case 'add':
    personalTableRef.value?.setSeleted(undefined)
    selectedRowId.value = undefined // 重置选中行
    // 启用编辑
    fromItems.value.forEach((item) => {
      if (item.prop !== 'age' && item.prop !== 'gender') {
        item.disabled = false
      }
    })
    break
    // 选择套餐
  case 'selectPackage':
    showSelectPackageDialog.value = true
    break
    //   // 加项
    // case 'additions':
    //   if (!packageId.value) {
    //     ElMessage.error('请先选择套餐!')
    //   } else {
    //     // 过滤出套餐项目组合
    //     packageItemList.value = rightTableData.value.filter((item) => {
    //       return item.isAdditional !== 1
    //     })
    //     // 过滤出加项项目组合
    //     selectedItemList.value = rightTableData.value.filter((item) => {
    //       return item.isAdditional === 1
    //     })
    //     showAdditionsDialog.value = true
    //   }
    //   break
    // 取消登记
  case 'deregistration':
    if (!registerId.value) {
      ElMessage.warning('请选择取消人员!')
    } else {
      showMessageBox('是否确认取消此体检登记？', {title: '提示', mesageType: 'base'})
        .then(() => {
          onCancelRegister() // 发起取消登记接口
        })
        .catch((error) => {
          console.warn(error)
        })
    }
    break
  }
}

/**
 * @description: 下乡体检模式
 * @return {*}
 */
const onSituationChange = (e) => {
  situationLoading.value = true
  // 切换内网环境，后端根据ip去ping当前是否是内网环境
  getJudgeSituation({innerIp: useUser.setup().store.userOrgInfor?.innerIp || ''})
    .then((res) => {
      situation.value = res.data?.data === 'outer' ? true : false
      situation.value === e ? ElMessage.success('切换成功！') : ElMessage.error('切换失败！')
      common.setSituation(res.data?.data) // 持久化内外网环境
    })
    .catch((err) => {
      console.warn(err)
      // 切换回去
      situation.value = !situation.value
    })
    .finally(() => {
      situationLoading.value = false
    })
}

/**
 * @description: 获取字典值
 * @return {*}
 */
const getDict = () => {
  seleteNationData.value.length = 0
  common.getDicData('nation').then((res) => {
    const arr: Array<SeleteData> = transfDicArrData(res)
    arr.forEach((item) => {
      seleteNationData.value.push(item)
    })
  })
  // 既往史下拉
  pastHistoryLsit.value.length = 0
  common.getDicData('past_history').then((res) => {
    res &&
      res?.forEach((item) => {
        pastHistoryLsit.value.push({label: item.dictItemName, value: item.dictItemName})
      })
  })
}

/**
 * @description: 获取社区下拉
 * @return {*}
 */
const getTeamSelect = () => {
  selectTeamLsit.value.length = 0
  getTeamListAll().then((res) => {
    res.data.data?.length &&
      res.data.data.forEach((item) => {
        selectTeamLsit.value.push({label: item.name, value: item.id || '', address: `${item.regionName || ''}${item.address || ''}`})
      })
  })
}

/**
 * @description: 根据性别、年龄查询对应的套餐
 * @return {*}
 */
const setDefaultPackage = () => {
  const params: GetPackageList = {
    age: formData.age,
    gender: formData.gender
  }
  formData.pastHistory ? (params.pastHistory = formData.pastHistory) : delete params.pastHistory
  getDefaultPackage(params)
    .then((res) => {
      const {data} = res.data
      packageId.value = data?.id || '' // 套餐id
      checkupPackageName.value = data?.packageName // 套餐名称
      checkupPackagePrice.value = data?.packagePrice // 套餐价格
      const dataArr: Array<RegisterItemGroups & RowOperbuttons> = []
      // 项目组合数据
      data?.itemGroupVOS?.length &&
        data?.itemGroupVOS.forEach((item) => {
          dataArr.push({...item, oper: []})
        })
      // 项目组合数据
      rightTableData.value = dataArr
    })
    .catch((err) => {
      console.warn(err)
    })
}

watch(
  () => formData.idNo,
  () => {
    // 输入完整身份证号时才触发
    if (formData.idNo && formData.idNo.length === 18) {
      const infor = getIdCardInfor(formData.idNo)
      formData.age = infor.age || ''
      formData.gender = infor.sex === 1 ? '男' : infor.sex === 2 ? '女' : ''
      // 根据身份证号查档案管理中的个人数据
      !selectedRowId.value &&
        getPersonalByIdNo({idNo: formData.idNo})
          .then((res) => {
            const {data} = res.data
            formData.personName = data?.name || ''
            formData.nation = data?.nation || ''
            formData.phone = data?.phone || ''
            formData.portrait = data?.portrait
            formData.teamId = data?.teamId || ''
            formData.address = data?.address || ''
            formData.pastHistory = data?.pastHistory
          })
          .catch((err) => {
            console.warn(err)
          })
      // 新增体检登记 根据性别、年龄查询对应的套餐
      !selectedRowId.value && formData.age && formData.gender && setDefaultPackage()
    } else {
      formData.age = ''
      formData.gender = ''
    }
  }
)

// 新增登记的时候修改既往史要修改套餐
watch(
  () => formData.pastHistory,
  () => {
    !selectedRowId.value && formData.age && formData.gender && setDefaultPackage()
  }
)

// 改变社区，居住地址跟着改变
watch(
  () => formData.teamId,
  () => {
    if (!selectedRowId.value) {
      if (formData.teamId) {
        const index = selectTeamLsit.value.findIndex((item) => {
          // 拿到社区名称
          item.value === formData.teamId && (formData.teamName = item.label)
          return item.value === formData.teamId
        })
        formData.address = selectTeamLsit.value[index]?.address
      } else {
        formData.address = ''
      }
    } else {
      const index = selectTeamLsit.value.findIndex((item) => {
        return item.value === formData.teamId
      })
      index === -1 && (formData.teamId = formData.teamName)
    }
  }
)

// 生命周期
onActivated(() => {
  IDReader.value = new HXGCReader()
  getTeamSelect()
  getPersonnelList()
})

onDeactivated(() => {
  IDReader.value = null
})

onBeforeMount(() => {
  getDict()
  loadCLodop()
})
</script>
<template>
  <page-container>
    <div class="box d-common-flex-row d-common-width-full">
      <div class="header-view">
        <d-header
          :show-loading="false"
          :search-rules="searchFromRules"
          :search-form-data="searchFromData"
          :search-form-items="searchFromItems"
          :search-buttons="serachButtons"
          :search-from-justify="'flexStart'"
          :search-from-full="true"
          @form-submit="onSubmit"
          @form-clear="onFormClear"
        >
          <template #idNo>
            <el-input v-model="searchFromData.idNo" placeholder="请输入身份证号">
              <template #suffix>
                <d-icon
                  :icon-config="{
                    icon: 'common-id-card',
                    type: 'custom',
                    size: 18,
                    color: ColorTheme
                  }"
                  @click="onReadIdCardHeader"
                />
              </template>
            </el-input>
          </template>
        </d-header>
        <span>下乡体检模式</span><el-switch v-model="situation" :loading="situationLoading" @change="onSituationChange" />
      </div>
      <div class="table-view">
        <div class="table-left d-common-flex-col">
          <p class="table-title">
            已登记人员列表
          </p>
          <d-table
            ref="personalTableRef"
            :show-header="false"
            :table-data="tableData"
            :show-loading="showLoading"
            :table-header-data="tableHeaderData"
            :default-seleted="defualtSeleted"
            :show-selection="true"
            :stripe="true"
            :default-multiple-selection="selectionData"
            @row-click="onRowClick"
            @multiple-selection="onMultipleSelection"
          >
            <template #personName="scope">
              <el-tooltip effect="dark" :content="scope.row.personName" placement="top">
                <a class="table-left-row-name" @click="openArchivesDialog(scope.row.idNo)">
                  {{ scope.row.personName }}
                </a>
              </el-tooltip>
            </template>
          </d-table>
          <d-footer :show-loading="showFooterLoading" :footer-buttons="footerButtonsLeft" class="personal-table-footer" @operation="onOperationLeft">
            <template #operbutton-prepend>
              <div class="table-left-total">
                共{{ tableData.length }}条数据
              </div>
            </template>
          </d-footer>
        </div>
        <div class="line" />
        <div class="table-right d-common-flex-col">
          <p class="table-title">
            登记信息
          </p>
          <div class="registration-infor">
            <el-avatar :src="formData.portrait" shape="square" @error="() => true">
              <img src="@/assets/image/default-avatar.png">
            </el-avatar>
            <d-from
              label-position="right"
              :label-width="80"
              :reset-fields-flag="resetFieldsFlag"
              :validate-flag="validateFlag"
              :rules="rules"
              :form-data="formData"
              :form-items="fromItems"
              :form-line-num="4"
              @submit="onRegister"
            >
              <template #idNo="scope">
                <el-input v-model="formData.idNo" placeholder="请输入身份证号" :disabled="scope.formitem.disabled">
                  <template v-if="!scope.formitem.disabled" #suffix>
                    <d-icon
                      :icon-config="{
                        icon: 'common-id-card',
                        type: 'custom',
                        size: 22,
                        color: ColorTheme
                      }"
                      @click="onReadIdCard"
                    />
                  </template>
                </el-input>
              </template>
              <template #age>
                <el-input v-model="formData.age" placeholder="请输入年龄" clearable disabled>
                  <template #append>
                    岁
                  </template>
                </el-input>
              </template>
            </d-from>
          </div>
          <div class="package-title">
            <span>套餐名称：</span>
            <span class="package-infor">{{ checkupPackageName }}</span>
            <!-- <span>套餐价格：</span>
            <span class="package-infor">￥{{ checkupPackagePrice }}</span>
            <span v-if="addItemGroupName">
              <span>加项：</span>
              <span class="package-infor">{{ addItemGroupName }}</span>
              <span>加项金额：</span>
              <span class="package-infor">￥{{ addItemGroupPrice }}</span>
            </span> -->
          </div>
          <d-table-promote
            :show-loading="showLoading"
            :show-header="false"
            :oper-buttons="[]"
            :search-form-items="[]"
            :search-buttons="[]"
            :table-data="rightTableData"
            :table-header-data="tableHeaderData2"
            :footer-buttons="footerButtonsRight"
            :show-footer="true"
            :stripe="true"
            :show-index="true"
            @operation="onOperationRight"
          >
            <template #oper="scope">
              <operation :row="scope.row" :col="scope.item" @opertion-click="cellOperation" />
            </template>
          </d-table-promote>
        </div>
      </div>
    </div>
  </page-container>
  <additions
    v-if="showAdditionsDialog"
    :show-dialog="showAdditionsDialog"
    :checkup-register-id="registerId"
    :package-id="packageId"
    :situation="situation"
    :package-item-list="packageItemList"
    :selected-item-list="selectedItemList"
    @close="showAdditionsDialog = false"
    @confirm="onAdditionsConfirm"
    @refresh="getPersonnelList()"
  />
  <selectPackage
    v-if="showSelectPackageDialog"
    :show-dialog="showSelectPackageDialog"
    :package-id="packageId"
    :age="formData.age"
    :gender="formData.gender"
    :past-history="formData.pastHistory || ''"
    @close="showSelectPackageDialog = false"
    @confirm="onSelectPackage"
  />
  <add-archives
    v-if="showArchivesDialog"
    :show-dialog="showArchivesDialog"
    dialog-type="edit"
    :archives-data="archivesData"
    :selete-nation-data="seleteNationData"
    :select-team-lsit="selectTeamLsit"
    :past-history-lsit="pastHistoryLsit"
    :id-reader="IDReader"
    :other-page-dialog="true"
    @close="onArchivesDialogClose()"
  />
</template>
<style scoped lang="less">
.table-view {
  flex: 1;
  display: flex;
  flex-flow: row nowrap;
  justify-content: space-between;
  border-top: 1px solid #e8eaec;
  column-gap: var(--d-margin-level-3);
  .table-title {
    margin: 14px 0;
    font-weight: bold;
  }
  .table-left {
    flex: 1;
    min-width: 210px;
  }
  .table-right {
    flex: 1.8;
  }
  .registration-infor {
    display: flex;
    form {
      width: 100%;
      margin-left: 10px;
      gap: 14px 12px !important;
      :deep(.el-form-item__error) {
        padding-top: 1px;
      }
    }
    .el-avatar {
      width: 98px;
      height: 120px;
      img {
        width: 98px;
        height: 120px;
      }
    }
    :deep(.el-input-group__append) {
      padding: 0 10px;
      background: #dcdee2 !important;
    }
  }
  .table-left-row-name {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    text-decoration: underline;
    color: var(--theme-color);
  }
  .personal-table-footer {
    height: 74px;
  }
  .table-left-total {
    width: 100%;
    line-height: 16px;
  }
}
.box {
  display: flex;
  flex-direction: column;
  flex: 1;
  height: 100%;
  .header-view {
    span {
      margin-right: 10px;
    }
  }
}
.line {
  width: 6px;
  height: 100%;
  background: var(--d-color-grey-1);
}
.package-title {
  margin-bottom: 10px;
}
.package-infor {
  color: var(--theme-color-error);
  margin-right: 70px;
  font-weight: bold;
}
</style>
